<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/1 0001
 * Time: 11:36
 */
namespace service;
use PHPExcel\IOFactory;
use PHPExcel;

class Excel{
    
    /**
     * 生成简单Excel通用方法
     * @param string  $fileName  导出文件名
     * @param array   $title 导出第一行标题数组
     * @param array   $data  导出的数据数组
     */
    public static function createSimpleExcel($fileName,$title,&$data){
        $objPHPExcel = new PHPExcel();
        $objActSheet = $objPHPExcel->getActiveSheet();

        $last = chr(64 + count($title));
        /*设置单元格的标题*/
        //设置font
        $objActSheet->getStyle('A1')->getFont()->setName('宋体')->setSize(10);
        //水平居中
        $objActSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objActSheet->getStyle('A1:'.$last.'1')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        //设置列宽
        $objActSheet->getDefaultColumnDimension('A')->setWidth(15);
        //赋值标题
        foreach($title as $k => $v){
            $firstord = chr(65 + $k);
            //赋值
            $objActSheet->setCellValueExplicit($firstord.'1', $v, \PHPExcel_Cell_DataType::TYPE_STRING);
        }
        //赋值数据
        $i = 2;
        foreach($data as $key =>$value){
            $j = 0;
            foreach($value as $v1){
                $firstord = chr(65 + $j);
                //strpos($k1,':') && $objActSheet->mergeCells($k1);
                $objActSheet->getStyle($firstord.($i+$key))->getFont()->setName('宋体')->setSize(10);
                $objActSheet->getStyle($firstord.($i+$key))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
                //赋值
                $objActSheet->setCellValueExplicit($firstord.($i+$key), $v1, \PHPExcel_Cell_DataType::TYPE_STRING);
                $j++;
            }
        }
        $fileName = iconv("utf-8", "gb2312", $fileName);
        $objPHPExcel->getActiveSheet()->setTitle($title);
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName.xls\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
    }
}